

int StorageInit(storage_buffer_t* sto,char* buffer,int buflen)
{
    if(sto == NULL || buffer == NULL || buflenth < CN_STORAGE_HEAD_LENGTH){
        return -1;
    }
    sto->buffer = buffer;
    sto->length = buflen;
    sto->in = 0;
    sto->out = 0;
    sto->counts = 0;
    pthread_mutex_init(&sto->lock,NULL);
    return 0;
}

int StorageClean(storage_buffer_t* sto)
{
    sto->length = 0;
    sto->in = 0;
    sto->out = 0;
    sto->counts = 0;
}

int StorageAddDatas(storage_buffer_t* buf,char* dat,int datalen)
{
    storage_t* ptr;
    int needlen,frees,toend;
    needlen =  datalen + CN_STORAGE_HEAD_LENGTH;
    if(needlen > buf->length){
        return -1;
    }

get_free:
#ifdef SMALL_LOCK_EN
    pthread_mutex_lock(&buf->lock);
#endif
    while(1){
        frees = buf->length - buf->counts;
        if(frees < needlen){
            ptr = (storage_t*)(buf->buffer + buf->out);
            toend = buf->length - buf->out;
            if((toend < CN_STORAGE_HEAD_LENGTH) || (ptr->len == CN_STORAGE_LENGTH_NONE)){
                buf->out = 0;
                buf->counts -= toend;
            }else{
                buf->counts -= ptr->len;
                buf->out += ptr->len;
            }
        }else{
            break;
        }
    }

    ptr = (storage_t*)(buf->buffer + buf->in);
    toend = buf->length - buf->in;
    if(toend < CN_STORAGE_HEAD_LENGTH ){
        buf->in = 0;
        buf->counts += toend;
        goto get_free;
    }else if(toend < needlen){
        ptr->len = CN_STORAGE_LENGTH_NONE;
        buf->in = 0;
        buf->counts += toend;
        goto get_free;
    }
//#ifdef SMALL_LOCK_EN
//    pthread_mutex_unlock(&buf->lock);
//#endif

    memcpy(ptr->datas,dat,datalen);
//#ifdef SMALL_LOCK_EN
//   pthread_mutex_lock(&buf->lock);
//#endif
    ptr->len = needlen;
    buf->in += needlen;
    buf->counts += needlen;
#ifdef SMALL_LOCK_EN
    pthread_mutex_unlock(&buf->lock);
#endif
    return needlen;
}


int StorageGetDatas(storage_buffer_t* buf,char* out,int buflen)
{
    int len,toend;
    storage_t* ptr;
    len = 0;
#ifdef SMALL_LOCK_EN
    pthread_mutex_lock(&buf->lock);
#endif
    while(buf->counts > 0){

        ptr = (storage_t*)(buf->buffer + buf->out);
        toend = buf->length - buf->out;
        if((toend<CN_STORAGE_HEAD_LENGTH)||(ptr->len == CN_STORAGE_LENGTH_NONE) ){
            buf->out = 0;
            buf->counts -= toend;
        }else{
            len = ptr->len - CN_STORAGE_HEAD_LENGTH;
            if(len <= buflen){
                memcpy(out,ptr->datas,len);
                buf->out += ptr->len;
                buf->counts -= ptr->len;
            }
            break;
        }

    }
#ifdef SMALL_LOCK_EN
    pthread_mutex_unlock(&buf->lock);
#endif
    return len;
}
